import { createSlice, nanoid, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export const loadTodos = createAsyncThunk(
  "todos/loadTodos",
  async (payload, { dispatch }) => {
    axios.get(payload).then((response) => {
      dispatch(setTodos(response.data));
    });
  }
);

const { actions, reducer: TodosReducer } = createSlice({
  name: "todos",
  initialState: [],
  reducers: {
    addTodo: {
      reducer(state, action) {
        state.push(action.payload);
      },
      // 预处理
      prepare(payload) {
        return {
          payload: {
            title: payload.title,
            id: nanoid(),
          },
        };
      },
    },
    setTodos(state, action) {
      action.payload.forEach((todo) => state.push(todo));
    },
  },
});

export const { addTodo, setTodos } = actions;
export default TodosReducer;
